package com.lagou.edu.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 胡益文
 * @since 2021/9/28 20:04
 */
public class Response {
    private OutputStream outputStream;

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public Response(OutputStream outputStream){
        this.outputStream = outputStream;
    }

    //输出
    public void output(String content) throws IOException {
        this.outputStream.write(content.getBytes());
    }

    /**
    * 功能描述:根据request的url获取html资源文件，并输出到浏览器端
     * @author: hyw
     * @return:
     * @since: 2021/9/28 20:36
    */
    public void outputHtml(String path) throws IOException {
        //根据相对路径获取绝对路径
        String absolutePath = "";
        if(path.startsWith("/")||path.indexOf(":")>-1){
            absolutePath = path;
        } else {
            absolutePath = ResourceUtil.getAbsolutePath(path);
        }
        File file = new File(absolutePath);
        if(file.exists()){
            //存在资源文件，则读取资源文件，并输出资源
            ResourceUtil.readAndOut(new FileInputStream(file),this.outputStream);
        }else{
            //输出404
            output(HttpProtocolUtil.getHttpHeader404());
        }

    }
}
